package test;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReenCond {
    ReentrantLock reentrantLock = new ReentrantLock();
    Condition notEmpty = reentrantLock.newCondition();
    Condition notFull = reentrantLock.newCondition();
    Queue<Integer> queue = new LinkedList<>();
    public static final int CAPACITY = 10;

    public static void main(String[] args) {
        ReenCond reenCond = new ReenCond();
        // 创建生产者和消费者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++) {
                    reenCond.produce(i);
//                    Thread.sleep(100); // 模拟耗时操作
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    reenCond.consume();
                    Thread.sleep(600); // 模拟耗时操作
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }

    public void produce(int value) throws InterruptedException {
        reentrantLock.lock();
        try {
            while (queue.size() == CAPACITY) {
                System.out.println("Produced await");
                notFull.await();
            }
            queue.add(value);
            System.out.println("Produced " + value);
            notEmpty.signal();
        } finally {
            reentrantLock.unlock();
        }
    }

    public void consume() throws InterruptedException {
        reentrantLock.lock();
        try {
            while (queue.isEmpty()) {
                System.out.println("Consume await");
                notEmpty.await();
            }
            int value = queue.poll();
            System.out.println("Consumed " + value);
            notFull.signal();
        } finally {
            reentrantLock.unlock();
        }
    }
}


